import { AfterViewInit, Component, OnDestroy, OnInit, ViewContainerRef } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Subscription } from 'rxjs';
import { GoodsModalComponent } from 'src/app/common/modal/goods-modal/goods-modal.component';
import { Condition } from 'src/app/models';
import { BaseService, DataRegisterService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { PermitConfig } from '../../../models';
import { EngineService } from '../../../services/engine.service';
import { BaseFieldComponent } from '../base-field/base-field.component';

@Component({
  selector: 'zepride-input-text',
  templateUrl: './input-text.component.html',
  styleUrls: ['../field.common.less', './input-text.component.less']
})
export class InputTextComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];

  inputValue: any;
  // 赋值标记，如果第一次进入，条件变化时不进行赋值
  unassigned = true;

  get borderClass() {
    if (this.componentData.extends && this.componentData.extends.border) {
      const border: 'no' | 'solid' | 'dashed' = this.componentData.extends.border; // no | solid | dashed
      return {
        'no-border': border === 'no',
        'border-solid': border === 'solid',
        'border-dashed': border === 'dashed'
      };
    } else {
      return '';
    }
  }

  get colorStyle() {
    const style: { color: string; backgroundColor: string } = {} as any;
    if (this.componentData.extends) {
      if (this.componentData.extends.color) {
        style.color = this.componentData.extends.color;
      }
      if (this.componentData.extends.backgroundColor) {
        style.backgroundColor = this.componentData.extends.backgroundColor;
      }
    }
    return style;
  }
  componentConditionChange$: Subscription;

  constructor(
    protected engineService: EngineService,
    protected baseSvr: BaseService,
    protected eventSvr: EventManagerService,
    protected orgSvr: OrganizationService,
    public uploadService: UploadService,
    protected msg: NzMessageService,
    private modal: NzModalService,
    private viewContainerRef: ViewContainerRef,
    protected dataRegisterService: DataRegisterService
  ) {
    super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dataRegisterService);
  }

  ngOnInit() {
    this.registerModelChange();
    this.registerConditionChange();
    if (this.bindData) {
      this.inputValue = this.reduction(this.bindData);
    } else {
      if (this.componentData.defaultValue != null && this.componentData.defaultValue != undefined) {
        this.inputValue = this.reduction(this.componentData.defaultValue);
        this.setBindData(this.enlarge(this.inputValue));
      }
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.setAuthorityData();
    }, 0);
  }

  inputChange(value) {
    const newValue = this.enlarge(value);
    this.setBindData(newValue);
  }

  enlarge(value) {
    let result = value;
    if (value && !isNaN(value) && this.componentData.extends.multiple) {
      result = parseFloat(value) * this.componentData.extends.multiple;
    }
    return result;
  }

  reduction(value) {
    let result = value;
    if (value && !isNaN(value) && this.componentData.extends.multiple) {
      result = parseFloat(value) / this.componentData.extends.multiple;
    }

    return result;
  }

  registerModelChange() {
    // .pipe(
    //   debounceTime(200)
    // )
    this.modelChange$ = this.engineService.dataModelChange$.subscribe(data => {
      if (data.identifyId !== this.componentData.identifyId && this.comparisonBindField(this.componentData.bindField, data.bindField)) {
        this.inputValue = this.reduction(this.bindData);
      }
    });
  }

  private comparisonBindField(sBindField: string, tBindField: string) {
    if (!sBindField) {
      return false;
    }
    if (tBindField.indexOf('.') > -1) {
      const tmpSplitList = tBindField.split('.');
      const has = tmpSplitList.find(x => x == sBindField);
      return has ? true : false;
    }

    if (sBindField.indexOf('.') > -1) {
      const tmpSplitList = sBindField.split('.');
      const has = tmpSplitList.find(x => x == tBindField);
      return has ? true : false;
    }

    return sBindField == tBindField;
  }

  registerConditionChange() {
    this.componentConditionChange$ = this.engineService.componentConditionChange$.subscribe(condition => {
      this.onConditionChange(condition);
    });
  }

  onConditionChange(condition: Condition) {
    if (condition.objectId === this.componentData.tmpComItemId && this.componentData.bindField) {
      const field = this.componentData.bindField;
      if (condition.result) {
        // if (this.unassigned) {
        //   this.unassigned = false;
        // } else {
        this.dataModel[field] = this.componentData.defaultValue;
        this.inputValue = this.reduction(this.componentData.defaultValue);
        // }
      }
    }
  }

  /**
   * 设置绑定字段的值
   * @param value 新的值
   */
  setBindData(value: any) {
    const bindField = this.componentData.bindField;
    if (bindField) {
      this.formatObj(value, bindField);
      this.setMapBindData(value);
      this.inputValue = this.reduction(value);
      this.dataModel[bindField] = value;
      // console.log('99999999', this.componentData.bindField, this.dataModel[this.componentData.bindField]);
      this.engineService.dataModelChange$.next({
        bindField,
        value,
        identifyId: this.componentData.identifyId,
        tmpComItemId: this.tmpComItemId,
        dataModel: this.dataModel,
        selector: this.componentData.selector
      });
    }
  }

  pageSavedHandle = async () => {
    if (!this.componentData.invalid && this.componentData.bindField) {
      this.dataModel[this.componentData.bindField] = this.enlarge(this.inputValue);
    }
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
    if (this.componentConditionChange$) {
      this.componentConditionChange$.unsubscribe();
    }
  }

  suffixFunc() {
    if (this.componentData.extends.suffixFunc == 'goodsModal') {
      const modalRef = this.modal.create({
        nzTitle: '选择品目',
        nzContent: GoodsModalComponent,
        nzFooter: null,
        nzViewContainerRef: this.viewContainerRef,
        nzComponentParams: {}
      });

      modalRef.afterClose.subscribe(result => {
        if (result) {
          this.inputValue = result.title;
          this.setBindData(this.inputValue);
        }
      });
    }
  }
}
